package practise.hibernate.dao.impl;

import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import practise.hibernate.dao.MoiveDao;
import practise.hibernate.persistence.MoiveRecord;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

@Service("moiveDao")
@Repository
@Transactional
public class MoiveDaoImpl implements MoiveDao {
    @PersistenceContext
    private EntityManager entityManager;

    @Override
    @Transactional(readOnly = true)
    public List<MoiveRecord> findAllMoivees(){

        final Query query = entityManager.createQuery("select distinct t from moive t");
        return query.getResultList();
    }

    @Override
    @Transactional(readOnly = true)
    public List<MoiveRecord> findByLocation(String name){
        final Query query = entityManager.createQuery("select distinct t from moive t where t.name = :name");
        query.setParameter("name" , name);
        return query.getResultList();
    }

    @Override
    @Transactional(readOnly = false)
    public void deleteMoive(int id){
        entityManager.remove(entityManager.find(MoiveRecord.class , id));
    }

    @Override
    @Transactional
    public MoiveRecord merge(MoiveRecord moive){
        return entityManager.merge(moive);
    }
}
